$(document).ready(function(e){
	var docs_viewer_url = "https://docs.google.com/viewer?url=";
	var msg_alert;
	var msg_timeout;
	
	$("<div />")
			.attr('id', 'ugdv_message')
			.css({
				 'z-index': 1001,
				 fontFamily: 'Arial, Helvetica, sans-serif',
				 display:'block',
				 position: 'fixed',
				 top: '0px',
				 padding: '3px 5px 3px 5px', 
				 textAlign: 'center',
				 backgroundColor: '#fff1a8',
				 fontWeight: 'bold',
				 '-webkit-border-bottom-left-radius':'3px',
				 '-webkit-border-bottom-right-radius':'3px'
			})
			.html("<b>Message Test</B>")
			.appendTo($("body"))
			.hide();
	
	function displayMessage(msg){
		$("#ugdv_message").html(msg);
		$("#ugdv_message").css({left: $(window).width() / 2 - $("#ugdv_message").width() / 2});
		$("#ugdv_message").fadeIn('fast');
		clearInterval(msg_timeout);
		msg_timeout = setInterval(hideMessage, 2000);
	}
	
	function hideMessage(){
		$("#ugdv_message").fadeOut('fast');
		clearInterval(msg_timeout);	
	}
	
	if (!/^https?:\/\/docs.google.com\/viewer/.test(document.URL.toString())){
		// xls|xlsx|ods|csv|tsv|txt|tsb|rtf|sxw
		// default extension regex if collection in prefs doesn't load
		var ugdv_valid_exp = new RegExp('^[^\\?#]+\\.(doc|docx|pdf|ppt|pps|tiff")((#|\\?).*)?$', 'i');
		var open_newTab = true;
		
		$("<div />")
			.addClass("ugdv_contextMenu")
			.attr('id', "ugdv_myMenu")
			.html("<ul id='ugdv_contextMenu'></ul>")
			.appendTo($("body"))
			.hide();
			
		$("<li />")
			.attr('id', "ugdv_menuItem_google_docs")
			.html("Open in Google Docs Viewer")
			.appendTo($("#ugdv_contextMenu"));
			
		$("<li />")
			.attr('id', "ugdv_menuItem_new_tab")
			.html("Open link in new tab")
			.appendTo($("#ugdv_contextMenu"));
		
		$("<li />")
			.attr('id', "ugdv_menuItem_new_window")
			.html("Open link in new window")
			.appendTo($("#ugdv_contextMenu"));
		
		$("<li />")
			.attr('id', "ugdv_menuItem_download_file")
			.html("Download file")
			.appendTo($("#ugdv_contextMenu"));
		
		$("<li />")
			.attr('id', "ugdv_menuItem_copy")
			.html("Copy link address")
			.appendTo($("#ugdv_contextMenu"));
		
		$("<li />")
			.addClass("ugdv_seperator")
			.appendTo($("#ugdv_contextMenu"));
		
		$("<li />")
			.attr('id', "ugdv_menuItem_import_docs")
			.html("Import into my Google Docs")
			.addClass('ugdv_disabled')
			.appendTo($("#ugdv_contextMenu"));
			
		$("<li />")
			.attr('id', "ugdv_menuItem_google_signin")
			.html("Login to Google Docs")
			.appendTo($("#ugdv_contextMenu"));	
			
		chrome.extension.sendRequest({
				type: 'logged_in'
			},
			function(response) {
				if (response === true){
					$('#ugdv_menuItem_import_docs').removeClass('ugdv_disabled');
					$('#ugdv_menuItem_google_signin').addClass('ugdv_disabled');
				}else{
					$('#ugdv_menuItem_import_docs').addClass('ugdv_disabled');
					$('#ugdv_menuItem_google_signin').removeClass('ugdv_disabled');
				}
			}
		);
		
		chrome.extension.sendRequest({
				type: 'get_ext'
			},
			function(response) {
				var used_ext = [];
				var prefs = response.split(",");
				if (response.length > 0){					
					for (var i = 0; i < prefs.length - 1; i++){
						var pref = prefs[i].split(":");
						if (pref[1] !== "false") used_ext.push(pref[0]);
					}
					ugdv_valid_exp = new RegExp('^[^\\?#]+\\.(' + used_ext.join('|') + ')((#|\\?).*)?$', 'i');
				}
				// get new tab
				var pref = prefs[prefs.length-1].split(":");
				open_newTab = pref[1] === "false" ? false : true;
				parsePageLinks();
				
			}
		);
		
		function parsePageLinks(){
			$("a").each(function(e){
				var link_href = this.href;
				if (ugdv_valid_exp.test(link_href)) {
					if (open_newTab) $(this).attr('target', "_blank");
					$(this).addClass("ugdv_link");
					this.href = docs_viewer_url + encodeURI(link_href);
				}
			});
			
			// attach context menu
			$(".ugdv_link").contextMenu("ugdv_myMenu",
				{
					shadow: true,
					bindings: {
						'ugdv_menuItem_google_docs': function(t) {
							var target_url = $(t).attr('href');
							if (open_newTab){
								chrome.extension.sendRequest({
										type: 'open_tab',
										url:target_url
									},
									function(response) {}
								);
							}else{
								window.location = target_url;
							}
						},
						'ugdv_menuItem_new_tab': function(t) {
							var target_url = $(t).attr('href').substring(docs_viewer_url.length, $(t).attr('href').length);
							chrome.extension.sendRequest({
									type: 'open_tab',
									url:target_url
								},
								function(response) {}
							);
						},
						'ugdv_menuItem_new_window': function(t) {
							var target_url = $(t).attr('href').substring(docs_viewer_url.length, $(t).attr('href').length);
							chrome.extension.sendRequest({
									type: 'open_win',
									url:target_url
								},
								function(response) {}
							);
						},
						'ugdv_menuItem_download_file': function(t) {
							displayMessage('Attempting to download file...');
							var target_url = $(t).attr('href').substring(docs_viewer_url.length, $(t).attr('href').length);
							window.location = "http://mycslab.com/file_helper.php?file=" + target_url;
						},
						'ugdv_menuItem_copy': function (t){
							var target_url = $(t).attr('href').substring(docs_viewer_url.length, $(t).attr('href').length);
							$("<input/>")
								.attr('id','ugdv_input')
								.css({width:'1px', height:'1px', border:'none', backgroundColor:'#FFF', 'position':'absolute'})
								.prependTo($(t).parent())
								.val(target_url)
								.focus()
								.select();
							
							document.execCommand("copy", false, null);
							$('#ugdv_input').hide(1, function(e){$(this).remove();});
							displayMessage('Link copied successfully.')
						},
						'ugdv_menuItem_import_docs': function(t, r) {
							if (!$(r).hasClass('ugdv_disabled')){
								displayMessage('Importing file to Google Docs...');
								var target_url = $(t).attr('href').substring(docs_viewer_url.length, $(t).attr('href').length);
								chrome.extension.sendRequest({
										type: 'send_to_docs',
										url: target_url
									},
									function(e) {
										if (e === true)
											displayMessage('File import successful : ' + target_url);
										else
											displayMessage('Are you logged in? File import failed.');
									}
								);
							}
						}, 
						'ugdv_menuItem_google_signin' : function(t, r) {
							if (!$(r).hasClass('ugdv_disabled')){
								chrome.extension.sendRequest({
										type: 'open_tab',
										url: 'http://docs.google.com'
									},
									function(response) {
										displayMessage('Opened Google Docs in new tab');
									}
								);
							}
						}
					}
				}							
			);
		}
	}else{
		chrome.extension.sendRequest({
				type: 'get',
				key: 'ugdv_useDocsLink'
			},
			function(e) {
				if (e == "true")
					$('#ugdv_import_link').show();
			}
		);
		
		var target_url = document.URL
		target_url = target_url.substring(docs_viewer_url.length, target_url.length);
		$('.links').append(' ');
		$("<a />")
			.attr('id', 'ugdv_import_link') 
			.addClass('link link-inactive')
			.html('Import into Google Docs')
			.appendTo($('.links'))
			.bind('click', function(e){
				if (!$(this).hasClass('link-inactive')){
					e.stopPropagation();
					displayMessage('Importing file to Google Docs...');
					chrome.extension.sendRequest({
							type: 'send_to_docs',
							url: target_url
						},
						function(e) {
							if (e === true)
								displayMessage('File import successful : ' + target_url);
							else
								displayMessage('Are you logged in? File import failed.');
						}
					);
				}
			})
			.hide();
			
		chrome.extension.sendRequest({
				type: 'logged_in'
			},
			function(response) {
				if (response === true){
					$('#ugdv_import_link').removeClass('link-inactive');
				}else{
					$('#ugdv_import_link').addClass('link-inactive');
				}
			}
		);
	}
});